Page({
  data: {
    publishedTopics: []
  },

  onLoad: function() {
    this.getUserInfo();
  },

  getUserInfo: function() {
    // 从本地存储获取手机号
    const userInfo = wx.getStorageSync('userInfo');
    const phoneNumber = userInfo.phone
    console.log(phoneNumber)
    
    if (!phoneNumber) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000
      });
      // 跳转到登录页面
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/login/login'
        });
      }, 2000);
      return;
    }

    this.queryPublishedTopics(phoneNumber);
  },

  async queryPublishedTopics(phoneNumber) {
    try {
      const db = wx.cloud.database();
      const _ = db.command;

      // 查询用户发布的所有话题
      const topics = await db.collection('topics')
        .where({
          'author.phone': phoneNumber
        })
        .get();
        console.log(topics)
      this.setData({
        publishedTopics: topics.data
      });
    } catch (error) {
      console.error('查询失败:', error);
      wx.showToast({
        title: '查询失败，请检查网络或联系管理员',
        icon: 'none'
      });
    }
  },

  gotoEditPage: function(e) {
    const topicId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/edit-topic/edit-topic?id=' + topicId
    });
  },

  async deleteTopic(e) {
    const topicId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定要删除这个话题吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            const db = wx.cloud.database();
            await db.collection('topics')
              .doc(topicId)
              .remove();

            wx.showToast({
              title: '删除成功',
              icon: 'success'
            });

            // 刷新话题列表
            this.getUserInfo();
          } catch (error) {
            console.error('删除失败:', error);
            wx.showToast({
              title: '删除失败，请重试',
              icon: 'none'
            });
          }
        }
      }
    });
  }
});